<template>
	<view class="myInquiry">
		<view class="titleBox bbf1">
			<view class="titleBoxL">
				<view class="" @tap="show = true">
					<view class="">
						{{date ? date : '日期'}}
					</view>
					<!-- <image class="down ml8"  referrerPolicy='no-referrer' :src="item.show ? 'https://wx.xtwaixie.com/imgdown1.png' : 'https://wx.xtwaixie.com/img/down.png'" /> -->
					<image class="down ml8" src="https://wx.xtwaixie.com/img/down.png" />
				</view>
				<view class="" @tap="showSelect = true">
					<view class="">
						{{selectType ? selectType : '来源'}}
					</view>
					<image class="down ml8" src="https://wx.xtwaixie.com/img/down.png" />
				</view>
			</view>
		</view>
		<view class="" style="height: 89rpx;">

		</view>
		<view v-if="join_in">
			<view v-if="list.length != 0">
				<view class="inquiryBox" v-for="(item, index) in list" :key="index" @click="demandDetails(item.id)">
					<view class="inquiryBoxTitle">
						<view class="">
							询价日期:{{ item.created_at }}
						</view>
						<view class="">

							来源：{{ item.source === 1 ? '主页' : item.source === 2 ? '详情' : item.source === 3 ? '推荐' : '主页'}}


						</view>
					</view>
					<view class="df ac sb" style="width: 100%;height:200rpx;min-height: 200rpx;">
						<view class="left">
							<view class="spare_parts_name f13"
								:style="item.file.length != 0 || item.drawing.length != 0 ? 'height:calc(200rpx - 34rpx);' : '100%'">
								{{ item.spare_parts_name }}
							</view>
							<view class="orderNum mt5 f13" v-if="item.file.length != 0 || item.drawing.length != 0">
								附件: <text
									style="text-decoration: underline;">{{ item.file.length + item.drawing.length }}</text>
							</view>
						</view>
						<view class="right df" style="flex:1">
							<!-- un_read -->
							<view style="white-space: nowrap;"
								:class=" item.is_read === 0 ? 'orderBtn2 mb5 un_read' : 'orderBtn2 mb5' "
								@click.stop="goPage('/subPack/receivedInquiry/inquiryDetail',item.id)">
								查看询价
							</view>
						</view>
					</view>
				</view>
				<view style="height: 30rpx;"></view>
			</view>
			<view class="df jc mt30" v-else style="flex-direction: column;align-items: center;">
				<image src="https://wx.xtwaixie.com/img/empty.png" style="width: 300rpx;" mode="widthFix"></image>
				<view class=""
					style="font-weight: bold;font-size: 32rpx;margin-top: 50rpx;margin-bottom:20rpx;color: #6b758c;">
					暂无收到的询价
				</view>
			</view>
		</view>
		<view class="" v-else>
			<image style="width: 200rpx;display: block;margin: 350rpx auto 0rpx;max-height:200rpx;"
				:src="getImgSrc('/uploads/20241102/17305268596725be8b0a4e4.png')" mode="widthFix"></image>
			<view class="f600 f18 mt20" style="text-align: center;">
				暂无权限
			</view>
			<view class="f14 mt10" style="text-align: center;color:gray">
				请先入驻供应商并完善企业资料
			</view>
			<view class="joinBtn" @click="goPage('/pages/settled/setPage')">
				立即入驻
			</view>
		</view>

		<!-- 需求下架 -->
		<van-popup :show="showDown" round>
			<p class="df ac jc pd200 mt5 w311">
				<span class="f16 c28 f500 tc" style="padding: 0px 30rpx;">下架后无法继续获得供应商报价。<br>确认后状态变更为“已完成”</span>
			</p>
			<view class="df ac btf1 h48 mt15">
				<p class="w50 tc f16 c28" @tap.native="showDown = false">取消</p>
				<button class="share-but1 h48 c10" @tap="downDemand">下架</button>
			</view>
		</van-popup>
		<van-popup :show="showSelect" @close="onClose" position="top">
			<view class="">
				<scroll-view :style="{height:`${status_arr.length * 96}rpx`}" :scroll-y="true">
					<ul class="db">
						<block v-for="(item, index) in status_arr" :key="index">
							<li class="pd015 h48 df ac sb" @tap.native="onTabs(item)">
								<p :class="'f14 c28 ' + (item === selectType ? 'c10' : '')">{{ item }}</p>
								<image class="sel" src="https://wx.xtwaixie.com/img/sel.png"
									v-if="item === selectType" />
							</li>
						</block>
					</ul>
				</scroll-view>
			</view>
		</van-popup>
		<van-popup :show="showType" @close="onClose" position="top">
			<view class="">
				<scroll-view :style="{height:`${type_arr.length * 96}rpx`}" :scroll-y="true">
					<ul class="db">
						<block v-for="(item, index) in type_arr" :key="index">
							<li class="pd015 h48 df ac sb" @tap.native="onType(item)">
								<p :class="'f14 c28 ' + (item === typeName ? 'c10' : '')">{{ item }}</p>
								<image class="sel" src="https://wx.xtwaixie.com/img/sel.png" v-if="item === typeName" />
							</li>
						</block>
					</ul>
				</scroll-view>
			</view>
		</van-popup>
		<van-popup :show="show" round position="bottom" @cancel='cancel'>
			<van-datetime-picker type="date" :value="currentDate" :min-date="minDate" :max-date="maxDate"
				@confirm='input($event,0)' @cancel='cancel' title='开始时间' />
		</van-popup>
		<van-popup :show="showsecondTime" round position="bottom">
			<van-datetime-picker type="date" :value="currentDates" :min-date="minDates" :max-date="maxDate"
				@confirm='input($event,1)' @cancel='cancel' title='截止时间' />
		</van-popup>
		<!-- <van-popup :show="Incomplete"
			custom-style="padding:30rpx 30rpx 20rpx 30rpx;border-radius:18rpx;font-size:26rpx;width:76%;" :round="true"
			:close-on-click-overlay="true">
			<view class="f16" style="text-align: center;">
				请完善企业资料
			</view>
			<view class="restart" @click="goPage('/pages/Factoryinformation/Factoryinformation')">
				立即完善
			</view>
		</van-popup> -->

		<!-- <van-popup :show="supVip"
			custom-style="padding:30rpx 30rpx 20rpx 30rpx;border-radius:18rpx;font-size:26rpx;width:76%;" :round="true"
			:close-on-click-overlay="true">
			<view class="f16" style="text-align: center;">
				未开通超级会员
			</view> -->
		<!-- <view class="restart" @click="goPage('/pages/Factoryinformation/Factoryinformation')">
				立即完善
			</view> -->
		<!-- </van-popup> -->
	</view>
</template>

<script>
	import {
		verifyPhoneNumber
	} from "@/utils/util"
	import http from '../../utils/http';
	export default {
		data() {
			return {
				currentDate: new Date().getTime(),
				currentDates: '',
				minDates: '',
				firstTime: '',
				secondTime: '',
				showsecondTime: false,
				type: 1,
				show: false,
				date: '',
				selectType: '',
				typeName: '',
				showType: false,
				minDate: new Date(2022, 0, 1).getTime(),
				maxDate: new Date().getTime(),
				status_arr: ['所有询价', '主页', '详情', '推荐'],
				type_arr: ['工厂询价', '大厅询价'],
				showSelect: false,
				page: 1,
				pagesize: 10,
				list: [],
				index: 0,
				showDown: false,
				Incomplete: false,
				detailUrl: '/pages/editSettled/editSettled',
				join_in: false,
				info_data: null,
				info: null,
				// supVip: false,
				start_date: '',
				end_date: '',
				pageTotal: 1,
				callback: null
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			// this.list = []
			this.page = 1
			let token = uni.getStorageSync('token')
			if (token) {
				this.getList();
				this.getUserInfo()
			}
		},
		onShow() {
			// 验证是否登录，是否有手机号
			this.callback = verifyPhoneNumber()
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			clearTimeout(this.callback)
		},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			if (this.pageTotal > this.page) {
				this.page++
				this.getList();
			} else {
				uni.showToast({
					title: '没有更多了~',
					icon: 'none'
				});
			}
		},
		methods: {
			getUserInfo() {
				http.request('user/userInfo').then((res) => {
					this.info = res.data.userInfo
					res.data.userInfo.grade === 0 ? this.join_in = false : this.join_in = true

					if (res.data.userInfo.grade != 0) {
						// res.data.userInfo.grade === 2 && res.data.userInfo.grade_type === 1 ? this.supVip = false : this.supVip = true

						http.request('user/settledInfo').then((res) => {
							this.info_data = res.data.info
							this.settledStatus = res.data.info.settledStatus

							if (!this.info.settledStatus) {
								console.log(this.info.settledStatus);
								this.detailUrl = '/pages/editSettled/editSettled'
							} else {
								if (this.info_data.detail && this.info_data.detail.status == 2) {
									this.detailUrl = '/pages/companyDetail/companyDetail?id=' + this.info
										.id
								} else {
									this.detailUrl = '/pages/Factoryinformation/Factoryinformation'
								}
							}

							if (this.detailUrl != '/pages/companyDetail/companyDetail?id=' + this.info
								.id && this.info_data.status != 1) {
								this.Incomplete = true
							}
						}).catch((res) => {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						});
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				});
			},
			onClose() {
				this.showSelect = false
				this.showType = false
			},
			cancel() {
				this.show = false
				this.showsecondTime = false
			},
			seemore(e) {
				if (e.quotation_count != 0) {
					uni.navigateTo({
						url: "/pages/receivedQuotation/receivedQuotation?id=" + e.id
					})
				} else {
					uni.showToast({
						title: "暂无报价",
						icon: "none"
					})
				}

			},
			demandDetails(id) {
				uni.navigateTo({
					url: "/subPack/receivedInquiry/inquiryDetail?&id=" + id
				})
			},
			input(e, i) {
				var date = new Date(e.detail); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				var Y = date.getFullYear() + '-';
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var D = date.getDate();
				if (i === 0) {
					this.currentDates = e.detail
					this.minDates = e.detail
					this.firstTime = Y + M + D
					this.show = false
					this.showsecondTime = true
				} else {
					this.secondTime = Y + M + D
					this.showsecondTime = false
					this.date = `${this.firstTime} - ${this.secondTime}`
					this.page = 1
					this.list = []
					this.getList()
				}
			},
			getList() {
				const data = {
					page: this.page,
					pagesize: 10,
					start_date: this.firstTime,
					end_date: this.secondTime,
					source: this.selectType == '主页' ? 1 : this.selectType == '详情' ? 2 : this.selectType == '推荐' ? 3 :
						this.selectType == '后台' ? 4 : 0
				};
				http.request('user/myDemandAdd', data)
					.then((res) => {
						res.data.data.forEach((i) => {
							// i.file = JSON.parse(i.file) || []
							// i.drawing = JSON.parse(i.drawing) || []
							try {
								i.drawing = JSON.parse(i.drawing) || []
							} catch (e) {
								console.error('parsing drawing failed:', e);
								i.drawing = [];
							}
							try {
								i.file = JSON.parse(i.file) || []
							} catch (e) {
								console.error('parsing file failed:', e);
								i.file = [];
							}
							this.list.push(i);
						});
						console.log(list, "list")
						this.pageTotal = this.calculateTotalPages(res.data.total, 10)
					})
					.catch((res) => {
						// uni.showToast({
						// 	title: res.message,
						// 	icon: 'none'
						// });
					});
			},
			calculateTotalPages(total, itemsPerPage) {
				return Math.ceil(total / itemsPerPage);
			},
			timeChange(e) {
				let y = e.getFullYear()
				let m = e.getMonth() + 1
				m = m < 10 ? ('0' + m) : m
				let d = e.getDate()
				d = d < 10 ? ('0' + d) : d
				return y + '-' + m + '-' + d;
			},
			onTabs(e) {
				console.log(e);
				this.selectType = e
				this.showSelect = false
				this.page = 1
				this.list = []
				this.getList()
			},
			onType(e) {
				this.typeName = e
				console.log(this.typeName)
				this.showType = false
				this.page = 1
				this.list = []
				this.getList()
			},
			goAdd() {
				uni.navigateTo({
					url: '/pages/demand/subDemand'
				})
			},
			onDown(index) {
				this.index = index
				this.showDown = true
			},
			goPage(url, id) {
				if (url == '/subPack/receivedInquiry/inquiryDetail') {
					// 检查用户是否已经订阅过
					const hasSubscribed = uni.getStorageSync('hasSubscribed');
					const that = this
					if (!hasSubscribed) {
						// 用户未订阅，请求订阅
						uni.requestSubscribeMessage({
							tmplIds: ['X5UgYbTKPQn_PmMMUKoZOV7iH_ON5vpemjP4QThHFjo'], // 替换为你的模板 ID
							success(res) {
								// 判断用户是否同意订阅
								if (res['X5UgYbTKPQn_PmMMUKoZOV7iH_ON5vpemjP4QThHFjo'] === 'accept') {
									// 用户同意订阅，存储订阅成功的状态
									uni.setStorageSync('hasSubscribed', true); // 标记为已订阅
									console.log('用户成功订阅');

								}
								that.jumpPage(url, id)
							},
							fail(err) {
								that.jumpPage(url, id)
							}
						});
					} else {
						that.jumpPage(url, id)
					}
				} else {
					this.jumpPage(url, id)
				}
			},
			jumpPage(url, id) {
				uni.navigateTo({
					url: id ? url + '?id=' + id : url,
				})
			},
			// 下架
			downDemand() {
				let data = {
					id: this.list[this.index].id
				};
				http.request('user/downDemand', data)
					.then((res) => {
						if (this.list[this.index].status == 2) {
							this.list[this.index].status = 3
							this.list[this.index].reject_content = '自助下架订单'
						} else {
							this.list[this.index].status = 4
						}
						this.showDown = false
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					})
					.catch((res) => {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					});
			},
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #F7F8FC;
	}

	.orderBtn2 {
		border: 2rpx solid #0239BA;
		padding: 8rpx 25rpx;
		border-radius: 10rpx;
		color: #FFF;
		margin-left: 20rpx;
		font-size: 28rpx;
		font-weight: bold;
		background-color: #0239BA;
	}

	.un_read {
		position: relative;

		&::after {
			content: '';
			width: 14rpx;
			height: 14rpx;
			position: absolute;
			top: 8rpx;
			right: 8rpx;
			background: red;
			border-radius: 50%;
		}
	}

	.orderNum {
		font-size: 24rpx;
		color: #0239BA;
	}

	.left {
		width: calc(100% - 220rpx);
		height: 100%;

		.spare_parts_name {
			width: 100%;
			display: -webkit-box;
			/* 对应 flexbox */
			-webkit-box-orient: vertical;
			/* 垂直方向 */
			-webkit-line-clamp: 4;
			/* 限制为四行 */
			overflow: hidden;
			/* 隐藏超出的文本 */
			text-overflow: ellipsis;
			/* 省略号 */
			line-height: 1.5;
			/* 行高（可根据需要调整） */
			max-height: 6em;
			/* 最大高度，根据行高和行数计算 1.5 * 4 */
		}
	}

	.right {
		margin-left: 30rpx;
		width: 190rpx;
		height: 100%;
		align-items: flex-end;
	}

	.myInquiry {
		.inquiryBox {
			width: 700rpx;
			box-sizing: border-box;
			margin: 20rpx auto;
			background-color: #FFF;
			padding: 20rpx 30rpx;
			border-radius: 20rpx;

			.inquiryBoxTitle {
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: 2rpx solid #EBEBED;
				padding-bottom: 20rpx;
				margin-bottom: 20rpx;

				view {
					font-size: 26rpx;
					color: #9DA2B6;
				}
			}

			.orderBtnBox {
				display: flex;
				justify-content: space-between;

				.orderTime {
					font-size: 24rpx;
					color: #9DA2B6;
				}

				.orderBtn {
					display: flex;
					align-items: center;

					.orderBtn1 {
						padding: 5rpx 20rpx;
						border: 2rpx solid #0239BA;
						border-radius: 10rpx;
						color: #0239BA;
						font-size: 28rpx;
						font-weight: bold;
					}

				}
			}

			.orderBox {
				display: flex;
				align-items: center;
				justify-content: space-between;
				flex-wrap: wrap;
				margin-bottom: 15rpx;

				.orderTitle {
					font-size: 28rpx;
					color: #000;
					font-weight: bold;
				}

				.orderType {
					font-size: 30rpx;
					font-weight: bold;
				}



				.orderError {
					font-size: 28rpx;
					color: #F00;
					font-weight: bold;
				}
			}
		}

		.titleBox {
			position: fixed;
			display: flex;
			justify-content: space-between;
			align-items: center;
			top: 0;
			left: 0;
			width: 750rpx;
			box-sizing: border-box;
			height: 88rpx;
			padding: 0 25rpx;
			background-color: #FFF;

			.titleBoxL {
				display: flex;
				align-items: center;

				>view {
					width: 150rpx;
					display: flex;
					justify-content: center;
					align-items: center;

					view {
						color: #6b758c;
						font-size: 28rpx;
						overflow: hidden;
						/*   超出容器的部分影响  */
						white-space: nowrap;
						/*  文本不换行   */
						text-overflow: ellipsis;
						/*  超出容器的文本显示省略号  */
					}
				}
			}

			.titleBoxR {
				display: flex;
				justify-content: space-between;
				align-items: center;
				background-color: #0239BA;
				color: #FFF;
				padding: 5rpx;
				padding-left: 10rpx;
				border-radius: 50rpx;

				image {
					width: 38rpx;
					height: 38rpx;
					margin-left: 5rpx;
				}

				view {
					font-size: 28rpx;
				}
			}
		}

		.share-but1 {
			width: 50% !important;
			font-size: 32rpx;
			padding: 0 !important;
			margin: 0 !important;
			font-weight: 400;
			text-align: center;
			color: #283043;
			line-height: 96rpx;
			border-left: 1rpx solid #ebedf0;
		}
	}

	.joinBtn {
		width: 230rpx;
		margin: 100rpx auto 0;
		padding: 20rpx 20rpx;
		text-align: center;
		color: #fff;
		background-color: $xt-primary;
		border-radius: 10rpx;
	}
</style>